package eece261.dChatter;

import java.io.IOException;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.concurrent.BlockingQueue;

import android.util.Log;

public class dChatSender implements Runnable {
	
	// For logging.
	private static final String TAG = "dChatSender";
	
	private dChatMessage    			out_msg_;
	//used to append messages from ChatWindow
	//Blocks until message is added
	private BlockingQueue<dChatMessage> msg_queue_;
	private MulticastSocket 			socket_;
	//ctor
	public dChatSender (MulticastSocket socket, BlockingQueue<dChatMessage> queue) {
		socket_    = socket;
		
		try {
			if (!socket_.getLoopbackMode())
				socket_.setLoopbackMode(true);
		} catch (SocketException e) {
			e.printStackTrace();
		}
			
		msg_queue_ = queue;
	}
	
    public void run () {
      //loop forever
      while (true) {
      
        try {
          //block until msg_queue is not empty
          out_msg_ = (dChatMessage)msg_queue_.take();
          socket_.send(out_msg_.packet());
          Log.d(TAG, "Message sent.");
        }

        catch (IOException e) {
			e.printStackTrace();
        } 
        catch (InterruptedException e) {
			e.printStackTrace();
		}
      }
    }
  }